// stock/bom_update/bom_update.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tableName: '商品定义',
    fieldList: [
      {field_id: 'quote_goods', label: '商品名称',type: 'reference1',mainEntity: 'goods',showFields: 'goods_id,goods_name,goods_type,goods_model,goods_brand,goods_place,goods_unit',is_null: false,referenceFilterCondition:[
          '{"filters":[{"filterType":"bit","type":"bit","fieldName":"is_used","value":"true","operator":"="}],"type":"AND"}'
        ]}
      ,{field_id: 'goods_id', label: '商品编码',type: 'text',is_null: true,disabled:true}
      , {field_id: 'goods_unit_quantity', label: '数量',type: 'num',is_null: false}
      ,{field_id: 'goods_type', label: '商品类别',type: 'reference1',is_null: true, option: [],optionId: 'id',optionName: 'label',disabled:true}
      ,{field_id: 'goods_model', label: '规格型号',type: 'reference1',is_null: true,optionId: 'row_id',optionName: 'goods_model_name', option: [],disabled:true}
      ,{field_id: 'goods_brand', label: '品牌',type: 'reference1',is_null: true,optionId: 'row_id',optionName: 'goods_brand_name', option: [],disabled:true}
      ,{field_id: 'goods_place', label: '产地',type: 'reference1',is_null: true, option: [],optionId: 'id',optionName: 'label',disabled:true}
      ,{field_id: 'goods_unit', label: '单位',type: 'reference1',is_null: true,optionId: 'row_id',optionName: 'goods_unit_name', option: [],disabled:true}
    ],
    defData:{},
    formData:{
      goods_id: '',
      quote_goods:'',
      goods_type: '',
      ['goods_type;value']: '',
      goods_model: '',
      ['goods_model;value']: '',
      goods_brand: '',
      ['goods_brand;value']: '',
      goods_place:'',
      ['goods_place;value']: '',
      goods_unit: '',
      ['goods_unit;value']: '',
      goods_unit_quantity: 1,
      row_id: 0,
      parent_row_id: 0,
      bom_level: 1
    },
    goodsList: [],  //商品列表

    p_val: null,  //父级数据

    validFlag: false,             // 验证标识
    validObj: {},                 // 验证表单项

    isEdit: true,   //数据编辑状态

    editBtn: true, //编辑按钮
    saveBtn: true,  //保存按钮
    newBtn: true,    //保存新增按钮

  },

  // 记录验证表单项
  validIpt(e) {
    let { validObj, } = this.data
    this.data.validObj = {
      ...validObj,
      ...e.detail,
    };
  },
  //验证数据
  validForm(validObj){
    return new Promise((resolve, reject) => {
      let valid = Object.values(validObj).includes(false) ? false : true;
      resolve(valid)
    })
  },

  //布局中字段修改
  bindChange(e){
    let detail = e.detail,
      field = detail.field,
      id = field.field_id || field.fieldName,
      type = field.type,
      val = detail.val,
      formData = this.data.formData;
    formData[id] = val;
    if (id === 'quote_goods') {
      let goods = this.data.goodsList.find(item=>{
        return item.row_id == val;
      }),
        {formData} = this.data;
      if (!goods)return;

      this.setData({isEdit: true});
      wx.$each(formData,(key,val)=>{
        if (['goods_unit_quantity','row_id','quote_goods','bom_level','parent_row_id'].includes(key))return;
        formData[key] = goods[key];
      });
      formData.quote_goods = val;

      this.setData({formData});
      this.setData({isEdit: false});

    }
  },

  //绑定提交
  bindSubmit(e){
    let type = e.currentTarget.dataset.type;

    // 开启验证
    this.data.validObj = {};
    this.setData({
      validFlag: !this.data.validFlag,
    });
    wx.showLoading({mask: true});
    let {validObj} = this.data;
    this.validForm(validObj).then(valid => {
      if(valid) { // 表单验证通过
        let {formData,tableName} = this.data;
        console.log('表单验证通过');
        let post = wx.$extend(formData);
        wx.$each(post,(key,val)=>{
          if (key.indexOf(';')>=0){
            delete post[key]
          }
        });
        delete post.goods_id;
        wx.$post(1,'Stock/update_bom',post).then(res=>{
          if (res.errcode !=0)return;
          wx.$toast('保存成功！');
          this.refreshList(formData.row_id,formData.parent_row_id);

          //关闭
          if (type === 'close'){
            wx.navigateBack({ //跳转到前一个页面
              delta:1,//前一个页面
            });
          }
          //清空
          if (type === 'clear'){
            formData = {
              goods_id: '',
              quote_goods:'',
              goods_type: '',
              ['goods_type;value']: '',
              goods_model: '',
              ['goods_model;value']: '',
              goods_brand: '',
              ['goods_brand;value']: '',
              goods_place:'',
              ['goods_place;value']: '',
              goods_unit: '',
              ['goods_unit;value']: '',
              goods_unit_quantity: 1,
              row_id: 0,
              parent_row_id: formData.parent_row_id,
              bom_level: formData.bom_level
            };
            tableName = '新增商品';
          }
          this.setData({isEdit: true});
          this.setData({
            formData,
            tableName
          });
          this.setData({isEdit: false});
      });

      } else {  // 表单验证不通过
        console.log('表单验证不通过');
        wx.$toast('必填项不能为空！')
      }
    })
  },

  //刷新列表
  refreshList(id,pid){
    const pages = getCurrentPages();//获取页面栈
    const beforePage = pages[pages.length - 2];  //前一个页面

    let {p_index,s_index} = this.data;

    beforePage.refreshData(id,s_index,pid,p_index);
  },

  //获取下拉选项
  getOptionsList(arg){
    let [key,v,url,post,iseach,parse] = arg;
    return new Promise((resolve,reject) => {
      wx.$post(v, url, post).then(res=>{
        if (res.errcode != 0){
          reject();
          return;
        }
        let data = res.data.row || [],
          list = data;
        if (iseach){
          list = this.eachData(data,'row_id',parse);
        }
        resolve({[key]: list});
      });
    });
  },

  initData(){
    let bomData = wx.getStorageSync('bomData');
    wx.removeStorageSync('bomData');
    let {type,p_index,p_val,s_index,s_val} = bomData,
      {formData} = this.data,
      obj = {},
      tableName = '新增商品';
      this.data.p_index = p_index;
      this.data.s_index = s_index;

    //传入父级信息
    if (p_val){
      formData.parent_row_id = p_val.row_id;
      formData.bom_level = p_val.bom_level+1;
      obj = {p_val,formData};
    }
    //传入当前编辑信息
    if (s_val){
      wx.$each(formData,(key,val)=>{
        formData[key] = s_val[key];
      });
      formData['quote_goods;value'] = s_val.goods_name;  //显示
      tableName = '编辑商品';
      obj = {...obj,formData};
    }

    obj = {...obj,tableName};
    this.setData(obj);
    this.setData({isEdit: false});

  },

  ready(){
    this.getOptionsList(['goods',3,'DynamicQuery/query_dynamic_v3',{"table_id":"goods","oby":"goods.row_id desc","page":1,"limit":0,"SearchWhere":{"filters":[{"CompareValue":"true","CompareWith":"goods.is_used","Operator":"=","or":1}],"type":"AND"}}]).then(res=>{
      this.data.goodsList = res.goods;
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    this.initData();
    this.ready();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
